package history.hot100;

import java.util.ArrayList;
import java.util.List;

// 39. 组合总和:https://leetcode-cn.com/problems/combination-sum/
// 题解：https://leetcode-cn.com/problems/combination-sum/solution/zu-he-zong-he-by-leetcode-solution/
public class LeetCode_39 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        List<Integer> combine = new ArrayList<Integer>();
        dfs(candidates, target,ans,combine,0);
        return ans;
    }

    private void dfs(int [] candidates, int target, List<List<Integer>>ans, List<Integer>combine, int idx) {
        if (idx == candidates.length) return;
        if (target == 0) {
            ans.add(new ArrayList<Integer>(combine));
            return;
        }
        dfs(candidates, target, ans, combine, idx+1);
        if (target - candidates[idx] >=0) {
            combine.add(candidates[idx]);
            dfs(candidates, target - candidates[idx], ans, combine, idx);
            combine.remove(combine.size()-1);
        }
    }
}
